import React from 'react';
import {
    StyleSheet,
    FlatList,
    View,
    Text,
    ActivityIndicator,
    Image,
} from 'react-native';

import CommunityGuidesCell from "./CommunityGuidesCell"
import CommunitySortView from "../sort/CommunitySortView"

const keywords = ["同人故事", "子女养成", "宠物养成", "活动玩法", "门派杂谈"]

const dataSource = [{
    "id": "1",
    "title": "关于高等级魔王竞技如何上排行",
    "content": "本人130+资深魔王玩家一枚，从神武手游刚刚出就一直在跟着游戏步伐走，虽然期间...",
    "img": "http://olpic.tgbusdata.cn/uploads/allimg/130225/38-130225115123133.jpg",
    "name": "霸气太子妃",
    "time": "3分钟前",
    "thumbup": "184",
    "comment": "127"
},
{
    "id": "2",
    "title": "[仰慕]鼠年吉祥，耗时一个月弄出来了",
    "content": "一个月的心血，没存神兽，就弄这个老鼠了，吃了47个元宵，音波太难打了，放弃了...",
    "img": "http://olpic.tgbusdata.cn/uploads/allimg/130225/38-130225115123133.jpg",
    "name": "秃哥",
    "time": "45分钟前",
    "thumbup": "61",
    "comment": "133"
},
{
    "id": "3",
    "title": "元宵排名活动攻略",
    "content": "元宵活动使用搜索慢慢来，相信大家拿到高级元宵福袋已经没什么问题了，而排名奖励每...",
    "img": "http://olpic.tgbusdata.cn/uploads/allimg/130225/38-130225115123133.jpg",
    "name": "小豆豆",
    "time": "5小时前",
    "thumbup": "4",
    "comment": "1"
},
{
    "id": "4",
    "title": "神宠技能之“业报轮回”",
    "content": "最近想给大家分享一下，小编总结的一只可以从低级带到高级，并且性价比还不逊的宠物...",
    "img": "http://olpic.tgbusdata.cn/uploads/allimg/130225/38-130225115123133.jpg",
    "name": "林深时见鹿",
    "time": "8小时前",
    "thumbup": "1",
    "comment": "0"
},
{
    "id": "5",
    "title": "龙宫灭门，建议全民土吸收。",
    "content": "今天一条突然发现，原来龙宫这么废，双龙秒二800对比武侯秒三1200真的受伤，...",
    "img": "",
    "name": "一生傲慢",
    "time": "02-09",
    "thumbup": "49",
    "comment": "81"
},
{
    "id": "6",
    "title": "换区",
    "content": "哪个区好",
    "img": "",
    "name": "轻鸟小宝",
    "time": "02-09",
    "thumbup": "14",
    "comment": "9"
},
]

export default class CommunityGuidesView extends React.Component {
    constructor(props) {
        super(props);
        this.canRequest = false

    }

    state = {
        dataList: dataSource,
        isRefresh: false,
        isLoading: true,
        page: 1,
        noData: false,
        hasMorePage: true,
        loadingMore: false,
        listHeight: 0,
        listSize: null
    }

    componentDidMount() {
        this.getShowData(1, 'refresh')
    }

    componentWillUnmount() {
        this.timer && clearTimeout(this.timer)
    }

    render() {
        if (this.state.isLoading) {
            return this.renderLoadingView()
        } else if (this.state.noData && !this.state.isLoading) {
            return this.renderEmptyView()
        } else if (!this.state.noData && !this.state.isLoading) {
            return this.renderMainView()
        }
    }

    renderLoadingView() {
        const { style } = this.props
        return (
            <View style={[styles.loading, style]}>
                <ActivityIndicator
                    animating={true}
                    color='gray'
                    size='large'
                />
            </View>
        )
    }

    renderEmptyView() {
        const { style } = this.props
        return (
            <View style={[styles.listEmpty, style]}>
                <Image style={styles.default_img}
                    source={{ uri: 'http://a3.att.hudong.com/68/61/300000839764127060614318218_950.jpg' }} />
                <Text style={styles.default_content}>未获取到数据</Text>
            </View>
        )
    }

    renderMainView() {
        const { style } = this.props
        return (
            <View style={[styles.container, style]}>
                <CommunitySortView style={styles.sortView}
                    dataList={keywords}
                    action={this.selectSortAction}
                />
                <FlatList style={styles.flatList}
                    data={this.state.dataList}
                    keyExtractor={this.keyExtractor}
                    renderItem={this.renderItem}
                    ItemSeparatorComponent={this.renderSeparator}
                    onScroll={this.onScroll}
                    onScrollBeginDrag={this.onScrollBeginDrag}
                    onScrollEndDrag={this.onScrollEndDrag}
                    onMomentumScrollBegin={this.onMomentumScrollBegin}
                    onMomentumScrollEnd={this.onMomentumScrollEnd}
                    refreshing={this.state.isRefresh}
                    onRefresh={this.onRefresh}
                    onEndReached={this.onEndReached}
                    onEndReachedThreshold={0.1}
                    ListFooterComponent={this.renderFooter}
                    contentContainerStyle={{ flexGrow: 1 }}
                    extraData={this.state}
                />
            </View>
        );
    }

    selectSortAction = (item) => {
        // console.log('选中了分类：' + item)
        // this.getShowData(1,'refresh')
    }

    onEndReached = () => {
        // console.log('onEndReached')
        this.requestMoreData()
    }

    requestMoreData = () => {
        // console.log('requestMoreData')
        if (!this.canRequest) return
        if (this.state.page * dataSource.length < this.state.listSize && !this.state.loadingMore) {
            this.setState({
                loadingMore: true
            }, () => {
                this.getShowData(this.state.page)
            })
        } else if (this.state.page * dataSource.length >= this.state.listSize && !this.state.loadingMore) {
            this.setState({
                hasMorePage: false
            })
        }
    }

    renderFooter = () => {
        if (this.state.hasMorePage && this.state.page >= 1) {
            return (
                <View style={styles.footer}>
                    <ActivityIndicator />
                    <Text style={{ marginLeft: 10 }}>正在加载更多数据...</Text>
                </View>
            )
        } else if (!this.state.hasMorePage && this.state.page >= 1) {
            return (
                <View style={{ height: 30, alignItems: 'center', justifyContent: 'flex-start', }}>
                    <Text style={{ color: '#999999', fontSize: 14, marginTop: 5, marginBottom: 5, }}>
                        没有更多数据了
                    </Text>
                </View>
            )
        } else {
            return (
                <View style={styles.footer}>
                    <Text></Text>
                </View>
            )
        }
    }

    onRefresh = () => {
        this.setState({
            isRefresh: true,
            page: 1
        }, () => {
            this.getShowData(1, 'refresh')
        })
    }

    getShowData = (page, type) => {
        this.timer = setTimeout(() => {
            if (type === 'refresh') {
                this.setState({
                    dataList: dataSource,
                    page: 1,
                    isRefresh: false,
                    isLoading: false,
                    noData: false,
                    loadingMore: false,
                    hasMorePage: true,
                    listSize: 300
                })
            } else {
                this.setState({
                    dataList: [...this.state.dataList, ...dataSource],
                    page: this.state.page + 1,
                    isRefresh: false,
                    isLoading: false,
                    noData: false,
                    loadingMore: false,
                    listSize: 300
                })
            }
        }, 50)
    }

    // 此函数用于为给定的item生成一个不重复的key
    keyExtractor = (item, index) => '' + index;

    renderItem = ({ item }) => {
        return (
            <CommunityGuidesCell data={item} />
        )
    }

    renderSeparator = () => {
        return (
            <View style={styles.separator} />
        )
    }

    onScroll = (event) => {
        let offSetY = event.nativeEvent.contentOffset.y
        let contentSizeHeight = event.nativeEvent.contentSize.height
        if (contentSizeHeight - offSetY < 2000) {
            this.requestMoreData()
        }
    }

    onScrollBeginDrag = () => {
        // console.log('onScrollBeginDrag');
        this.canRequest = true;
    }
    onScrollEndDrag = () => {
        // console.log('onScrollEndDrag');
        this.canRequest = false;
    }
    onMomentumScrollBegin = () => {
        // console.log('onMomentumScrollBegin');
        this.canRequest = true;
    }
    onMomentumScrollEnd = () => {
        // console.log('onMomentumScrollEnd');
        this.canRequest = false;
    }
}

const styles = StyleSheet.create({
    safeAreaView: {
        flex: 1
    },
    container: {
        flex: 1,
    },
    sortView: {
        height: 50,
        marginLeft: 0,
        marginRight: 0,
    },
    flatList: {

    },
    separator: {
        height: 0.5,
        marginRight: 0,
        backgroundColor: '#eeeeee',
        marginLeft: 10,
    },
    footer: {
        flexDirection: 'row',
        height: 24,
        justifyContent: 'center',
        alignItems: 'center',
        marginBottom: 10,
    },
    loading: {
        justifyContent: 'center',
        alignItems: 'center',
        flex: 1,
    },
    listEmpty: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
    },
    default_img: {
        width: 90,
        height: 90,
        marginBottom: 20,
        backgroundColor: '#eeeeee'
    },
    default_content: {
        fontFamily: 'PingFangSC-Regular',
        fontSize: 15,
        height: 21,
        color: '#CCCCCC',
        textAlign: 'center'
    }
})